import logging
from logging.handlers import RotatingFileHandler

from flask import g
from flask import render_template
from flask_wtf.csrf import generate_csrf
from config import config
import redis
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from sqlalchemy.orm import Session


#  数据库
db = SQLAlchemy()
redis_store = None  # type: StrictRedis


def Creat_app(config_name):
    """通过传入参数，初始化参数"""
    setup_log(config_name)
    app = Flask(__name__)
    #  配置
    app.config.from_object(config[config_name])
    #  配置数据库
    db.init_app(app)
    #  配置redis
    global redis_store
    redis_store = redis.StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT)

    @app.after_request
    def after_request(response):
        # 调用函数生成 csrf_token
        csrf_token = generate_csrf()
        # 通过 cookie 将值传给前端
        response.set_cookie("csrf_token", csrf_token)
        return response

     # 配置CSRF保护
    CSRFProtect(app)
     # 设置session保存位置
    Session(app)
    from info.utils.common import do_index_class
    #  注册蓝图
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)
    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)
    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)
    from info.modules.news import news_blu
    app.register_blueprint(news_blu)
    from info.utils.common import user_login_data
    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu, url_prefix="/admin")
    @app.errorhandler(404)
    @user_login_data
    def page_not_fount(e):
        user = g.user
        data = {"user": user.to_dict() if user else None}
        return render_template('news/404.html', data=data)

    # 添加过虑器
    app.add_template_filter(do_index_class, "index_class")
    return app


def setup_log(config_name):
    """配置⽇志"""
    #  设置⽇志的记录等级
    logging.basicConfig(level=config[config_name].LOG_LEVEL)  # 调试debug级
    #  创建⽇志记录器，指明⽇志保存的路径、每个⽇志⽂件的最⼤⼤⼩、保存的⽇志⽂件个数上限
    file_log_handler = RotatingFileHandler("./logs/log", maxBytes=1024*1024*100, backupCount=10)
    #  创建⽇志记录的格式⽇志等级输⼊⽇志信息的⽂件名⾏数⽇志信息
    formatter = logging.Formatter('%(levelname)s%(filename)s:%(lineno)d	%(message)s')
    # 为刚创建的⽇志记录器设置⽇志记录格式
    file_log_handler.setFormatter(formatter)
    #  为全局的⽇志⼯具对象（flask	app使⽤的）添加⽇志记录器
    logging.getLogger().addHandler(file_log_handler)


